﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using FikriKibar.Business.Abstract;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Exceptions;
using FikriKibar.Common.Helpers;
using FikriKibar.Common.Validation.FluentValidation.UserGroup;
using FikriKibar.DataAccess;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.Entities.Abstract;
using FikriKibar.Entities.Composite.BaseModels;
using FikriKibar.Entities.Composite.UserGroupModels;
using FikriKibar.Entities.Concrete;
using FikriKibar.Globalization;

namespace FikriKibar.Business.Concrete
{
    public class UserGroupManager : IUserGroupService
    {
        #region Global Declarations
        private readonly IUserGroupDal _userGroupDal = new EfUserGroupDal();

        private readonly IUserGroupLanguageLineDal _userGroupLanguageLineDal = new EfUserGroupLanguageLineDal();

        private readonly IUserGroupLanguageLineHistoryDal _userGroupLanguageLineHistoryDal = new EfUserGroupLanguageLineHistoryDal();

        private readonly IUserGroupHistoryDal _userGroupHistoryDal = new EfUserGroupHistoryDal();

        private readonly ILanguageDal _languageDal = new EfLanguageDal();

        private readonly ISettingDal _settingDal = new EfSettingDal();
        private readonly IUserGroupUserLineDal _userGroupUserLineDal = new EfUserGroupUserLineDal();
        #endregion
        #region Methods

        public AddModel<UserGroupLanguageLine> Add()
        {
            return new AddModel<UserGroupLanguageLine>
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void Add(AddModel<UserGroupLanguageLine> model)
        {
            var validator = new AddValidator(model);
            var userGroupLanguageLine = model.Item;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;


            var userGroup = new UserGroup
            {
                CreateDate = DateTime.Now,
                CreatedBy = fikriKibarIdentity.UserId,
                UpdatedBy = fikriKibarIdentity.UserId,
                UpdateDate = DateTime.Now

            };

            var addedUserGroup = _userGroupDal.Add(userGroup);

            foreach (var languageId in model.SelectedLanguageIds)
            {
                userGroupLanguageLine.UserGroupId = addedUserGroup.Id;
                userGroupLanguageLine.UserGroup = null;
                userGroupLanguageLine.LanguageId = languageId;
                userGroupLanguageLine.UserGroupName = model.Item.UserGroupName;
                userGroupLanguageLine.UserGroupDescription = model.Item.UserGroupDescription;
                userGroupLanguageLine.CreatedBy = fikriKibarIdentity.UserId;
                userGroupLanguageLine.CreateDate = DateTime.Now;
                userGroupLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                userGroupLanguageLine.UpdateDate = DateTime.Now;
                userGroupLanguageLine.DisplayOrder = addedUserGroup.Id;
                userGroupLanguageLine.IsApproved = model.Item.IsApproved;
                _userGroupLanguageLineDal.Add(userGroupLanguageLine);
            }
        }
        public UpdateModel Update(int id, string language)
        {
            var userGroupLanguageLine = _userGroupLanguageLineDal.Filter(e => e.UserGroupId == id && e.Language.LanguageCode == language).FirstOrDefault();

            if (userGroupLanguageLine == null) throw new NotFoundException();

            var userGroupUsers = new List<User>();

            var userGroupUserLines = _userGroupUserLineDal.Filter(e => e.UserGroupId == id);

            if (userGroupUserLines != null)
            {
                userGroupUsers.AddRange(userGroupUserLines.Select(item => item.User));
            }

            return new UpdateModel
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                SelectedLanguageCode = language,
                ItemId = id,
                Users = userGroupUsers,
                Item = userGroupLanguageLine
            };
        }
        public void Update(UpdateModel model)
        {
            var validator = new UpdateValidator(model);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var userGroup = _userGroupDal.GetById(model.ItemId);

            var userGroupHistory = new UserGroupHistory
            {
                UserGroupId = userGroup.Id,
                CreateDate = userGroup.CreateDate,
                CreatedBy = userGroup.CreatedBy,
                UpdateDate = userGroup.UpdateDate,
                UpdatedBy = userGroup.UpdatedBy,
                IsDeleted = false
            };
            _userGroupHistoryDal.Add(userGroupHistory);


            userGroup.UpdateDate = DateTime.Now;
            userGroup.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedUserGroup = _userGroupDal.Update(userGroup);

            var userGroupLanguageLine = _userGroupLanguageLineDal.Filter(e => e.UserGroupId == model.ItemId && e.Language.LanguageCode == model.SelectedLanguageCode).FirstOrDefault();

            if (userGroupLanguageLine == null)
            {
                userGroupLanguageLine = new UserGroupLanguageLine
                {
                    UserGroupId = affectedUserGroup.Id,
                    UserGroup = null,
                    LanguageId = _languageDal.GetByCode(model.SelectedLanguageCode).Id,
                    UserGroupName = model.Item.UserGroupName,
                    UserGroupDescription = model.Item.UserGroupDescription,
                    CreatedBy = fikriKibarIdentity.UserId,
                    CreateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    UpdateDate = DateTime.Now,
                    DisplayOrder = affectedUserGroup.Id,
                    IsApproved = model.Item.IsApproved
                };
                _userGroupLanguageLineDal.Add(userGroupLanguageLine);

            }
            else
            {
                var userGroupLanguageLineHistory = new UserGroupLanguageLineHistory
                {
                    UserGroupLanguageLineId = userGroupLanguageLine.Id,
                    UserGroupId = userGroupLanguageLine.UserGroupId,
                    LanguageId = userGroupLanguageLine.LanguageId,
                    UserGroupName = userGroupLanguageLine.UserGroupName,
                    UserGroupDescription = userGroupLanguageLine.UserGroupDescription,
                    CreateDate = userGroupLanguageLine.CreateDate,
                    CreatedBy = userGroup.CreatedBy,
                    UpdateDate = userGroup.UpdateDate,
                    UpdatedBy = userGroup.UpdatedBy,
                    DisplayOrder = userGroupLanguageLine.DisplayOrder,
                    IsApproved = userGroupLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _userGroupLanguageLineHistoryDal.Add(userGroupLanguageLineHistory);

                userGroupLanguageLine.UpdateDate = DateTime.Now;
                userGroupLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                userGroupLanguageLine.UserGroupName = model.Item.UserGroupName;
                userGroupLanguageLine.UserGroupDescription = model.Item.UserGroupDescription;
                userGroupLanguageLine.IsApproved = model.Item.IsApproved;
                _userGroupLanguageLineDal.Update(userGroupLanguageLine);
            }




        }
        public ListModel<UserGroupLanguageLine> GetList(string searchTerm, string languageCode, int status, int index, int size, string idsForSort, string idsForApprove, string idsForDelete)
        {
            var model = new ListModel<UserGroupLanguageLine>
            {
                Paging = new Paging(),
                ItemList = new List<UserGroupLanguageLine>(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };

            if (idsForDelete != null)
            {
                var ids = idsForDelete;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                DeleteSelected(idList, languageCode);

            }
            model.IdsForDelete = null;


            if (idsForApprove != null)
            {
                var ids = idsForApprove;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                ApproveSelected(idList, languageCode);
            }

            model.IdsForApprove = null;

            var sortHelper = new SortHelper<UserGroupLanguageLine>();
            sortHelper.OrderByDescending(t => t.DisplayOrder);

            model.Paging.CurrentPageSize = size;
            model.Paging.CurrentPage = index;
            model.SelectedStatus = status;

            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.Paging.TotalItemCount = _userGroupLanguageLineDal.GetTotalCount(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.Paging.TotalItemCount = _userGroupLanguageLineDal.GetTotalCount(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }

            var pageSizeListSetting = _settingDal.GetValueByKey("PageSizeList");
            var pageSizeSettingValue = "10,25,50,100";
            if (pageSizeListSetting != null)
            {
                pageSizeSettingValue = pageSizeListSetting;
            }
            var pageSizeList = pageSizeSettingValue.Split(',').Select(t => new KeyValuePair<int, string>(t.ConvertToInt(), t)).ToList();

            pageSizeList.Insert(0, new KeyValuePair<int, string>(-1, "[" + Resources.All + "]"));
            model.Paging.PageSizeList = pageSizeList;


            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _userGroupLanguageLineDal.Filter(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus, sortHelper, index, size) : _userGroupLanguageLineDal.Filter(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode && e.IsApproved == blStatus);
            }
            else
            {
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _userGroupLanguageLineDal.Filter(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode, sortHelper, index, size) : _userGroupLanguageLineDal.Filter(e => e.UserGroupName.Contains(searchTerm) && e.Language.LanguageCode == languageCode);
            }


            if (idsForSort != null)
            {
                var ids = idsForSort;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                model.ItemList = SaveSort(idList, languageCode);
            }
            model.IdsForSort = null;

            model.Searched = searchTerm;
            model.SelectedLanguageCode = languageCode;

            model.Paging.CurrentPage = index;
            model.Paging.TotalPageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / size);
            return model;
        }
        public void Delete(int id, string language)
        {
            var userGroupLanguageLine = _userGroupLanguageLineDal.Filter(e => e.Language.LanguageCode == language).FirstOrDefault(e => e.UserGroup.Id == id);
            if (userGroupLanguageLine == null) return;
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var userGroupLanguageLineHistory = new UserGroupLanguageLineHistory
            {
                UserGroupLanguageLineId = userGroupLanguageLine.Id,
                UserGroupId = userGroupLanguageLine.UserGroupId,
                LanguageId = userGroupLanguageLine.LanguageId,
                UserGroupName = userGroupLanguageLine.UserGroupName,
                UserGroupDescription = userGroupLanguageLine.UserGroupDescription,
                CreateDate = userGroupLanguageLine.CreateDate,
                CreatedBy = userGroupLanguageLine.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                DisplayOrder = userGroupLanguageLine.DisplayOrder,
                IsApproved = userGroupLanguageLine.IsApproved,
                IsDeleted = true
            };
            _userGroupLanguageLineHistoryDal.Add(userGroupLanguageLineHistory);
            _userGroupLanguageLineDal.Delete(userGroupLanguageLine);

            if (_userGroupLanguageLineDal.Filter(e => e.UserGroupId == id).Any()) return;
            var userGroup = _userGroupDal.GetById(id);
            if (userGroup == null) return;
            var userGroupHistory = new UserGroupHistory
            {
                UserGroupId = userGroup.Id,
                CreateDate = userGroup.CreateDate,
                CreatedBy = userGroup.CreatedBy,
                UpdateDate = DateTime.Now,
                UpdatedBy = fikriKibarIdentity.UserId,
                IsDeleted = true
            };
            _userGroupHistoryDal.Add(userGroupHistory);
            _userGroupDal.Delete(userGroup);
        }

        private List<UserGroupLanguageLine> SaveSort(IReadOnlyList<int> idList, string languageCode)
        {
            var returnedValue = new List<UserGroupLanguageLine>();
            for (var i = 0; i < idList.Count; i++)
            {
                var userGroupLanguageLine = _userGroupLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.UserGroup.Id == idList[i]);

                if (userGroupLanguageLine == null) continue;
                var userGroup = _userGroupDal.GetById(userGroupLanguageLine.UserGroup.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

                var userGroupHistory = new UserGroupHistory
                {
                    UserGroupId = userGroup.Id,
                    CreateDate = userGroup.CreateDate,
                    CreatedBy = userGroup.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _userGroupHistoryDal.Add(userGroupHistory);


                userGroup.UpdatedBy = fikriKibarIdentity.UserId;
                userGroup.UpdateDate = DateTime.Now;
                _userGroupDal.Update(userGroup);

                var userGroupLanguageLineHistory = new UserGroupLanguageLineHistory
                {
                    UserGroupLanguageLineId = userGroupLanguageLine.Id,
                    UserGroupId = userGroupLanguageLine.UserGroupId,
                    LanguageId = userGroupLanguageLine.LanguageId,
                    UserGroupName = userGroupLanguageLine.UserGroupName,
                    UserGroupDescription = userGroupLanguageLine.UserGroupDescription,
                    CreateDate = userGroupLanguageLine.CreateDate,
                    CreatedBy = userGroupLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = userGroupLanguageLine.DisplayOrder,
                    IsApproved = userGroupLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _userGroupLanguageLineHistoryDal.Add(userGroupLanguageLineHistory);


                userGroupLanguageLine.DisplayOrder = i + 1;
                userGroupLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                userGroupLanguageLine.UpdateDate = DateTime.Now;
                userGroupLanguageLine.UserGroup = userGroup;
                _userGroupLanguageLineDal.Update(userGroupLanguageLine);
                returnedValue.Add(userGroupLanguageLine);
            }
            return returnedValue;
        }
        private void ApproveSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                var userGroupLanguageLine = _userGroupLanguageLineDal.Filter(e => e.Language.LanguageCode == languageCode).FirstOrDefault(e => e.UserGroup.Id == id);
                if (userGroupLanguageLine == null) continue;
                var userGroup = _userGroupDal.GetById(userGroupLanguageLine.UserGroup.Id);
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var userGroupHistory = new UserGroupHistory
                {
                    UserGroupId = userGroup.Id,
                    CreateDate = userGroup.CreateDate,
                    CreatedBy = userGroup.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    IsDeleted = false
                };
                _userGroupHistoryDal.Add(userGroupHistory);
                userGroup.UpdatedBy = fikriKibarIdentity.UserId;
                userGroup.UpdateDate = DateTime.Now;
                _userGroupDal.Update(userGroup);

                var userGroupLanguageLineHistory = new UserGroupLanguageLineHistory
                {
                    UserGroupLanguageLineId = userGroupLanguageLine.Id,
                    UserGroupId = userGroupLanguageLine.UserGroupId,
                    LanguageId = userGroupLanguageLine.LanguageId,
                    UserGroupName = userGroupLanguageLine.UserGroupName,
                    UserGroupDescription = userGroupLanguageLine.UserGroupDescription,
                    CreateDate = userGroupLanguageLine.CreateDate,
                    CreatedBy = userGroupLanguageLine.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = fikriKibarIdentity.UserId,
                    DisplayOrder = userGroupLanguageLine.DisplayOrder,
                    IsApproved = userGroupLanguageLine.IsApproved,
                    IsDeleted = false
                };
                _userGroupLanguageLineHistoryDal.Add(userGroupLanguageLineHistory);


                userGroupLanguageLine.UpdatedBy = fikriKibarIdentity.UserId;
                userGroupLanguageLine.UpdateDate = DateTime.Now;
                userGroupLanguageLine.IsApproved = true;
                userGroupLanguageLine.UserGroup = userGroup;
                _userGroupLanguageLineDal.Update(userGroupLanguageLine);

            }
        }
        private void DeleteSelected(IEnumerable<int> idList, string languageCode)
        {
            foreach (var id in idList)
            {
                Delete(id, languageCode);
            }
        }

        #endregion
    }
}
